package com.lotus.minio.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import jakarta.annotation.PostConstruct;


@Component
public class MinIOUtil {

	@Value("${spring.minio.endpoint}")
	private String endpoint;
	
	@Value("${spring.minio.access-key}")
	private String accessKey;
	
	@Value("${spring.minio.secret-key}")
	private String secretKey;
	
	@Value("${spring.minio.bucket-name}")
	private String bucketName;
	
	@Value("${spring.minio.bucket}")
	private String bucket;
	
	
	private MinioClient minioClient;
	
	@PostConstruct
	public void init() {
		minioClient = MinioClient.builder()
				.endpoint(endpoint)
				.credentials(accessKey, secretKey)
				.build();
	}
	
	/**
     * 通用上传方法（自动分片）
     * @param file      文件对象
     * @param fileName  存储的文件名
     * @param partSize  分片大小(单位：字节；  <=0 表示不分片)
     */
    public String uploadFile(MultipartFile file, String fileName, long partSize) throws Exception{
        boolean exsists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if(!exsists){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }

        // 构造长传参数（partSize > 0 时自动分片）
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .stream(file.getInputStream(), file.getSize(), partSize)
                .contentType(file.getContentType())
                .build();
        

        //minioClient.putObject(
        //        PutObjectArgs.builder()
        //                .bucket(bucketName)
        //                .object(fileName)
        //                .stream(file.getInputStream(), file.getSize(), -1)
        //                .contentType(file.getContentType())
        //                .build()
        //);

        // 执行上传
        ObjectWriteResponse response = minioClient.putObject(args);

        return endpoint + "/" + bucketName + "/" + fileName;
    }
    
    
    /**
     * TODO: 下载文件(其他方法类似)
     */
    
    
}
